package com.tc.quartz.util;

import com.xiaoleilu.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.MessageFormat;

/**
 * quartz定时器项目工具类
 * @author yongjin.ye
 * 
 */
public class QrtzUtil implements ApplicationContextAware {

	protected static final Logger log = LoggerFactory.getLogger(QrtzUtil.class);
	
	//public static final ThreadLocal<StringBuffer> runLogBuffer = new ThreadLocal<StringBuffer>();

	/**
	 * web.xml中需要增加： <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	 */
	private static ApplicationContext applicationContext;
	
	/**
	 * 占位符替换
	 */
	public static String fmtMsg(String query, Object... values) {
		return MessageFormat.format(query, values);
	}

	public static String obj2json(Object... obj){
		try {
			return JSONUtil.toJsonStr(obj);
		} catch (Exception e) {
			log.error("obj转换json异常", e);
		}
		return null;
	}

	public static String obj2string(Object[] obj) {
		StringBuffer sbf = new StringBuffer();
		try {
			for (int i = 0; i < obj.length; i++) {
				sbf.append(org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(obj[i])).append("\r\n");
			}
		} catch (Exception e) {
			log.error("obj转换string异常", e);
		}
		return sbf.toString();
	}
	
	public static String substring(String str, int start, int end) {
		if(StringUtils.isEmpty(str)) return str;
		return str.substring(0, str.length() > end ? end : str.length());
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		QrtzUtil.applicationContext = applicationContext;
	}


	/**
	 * 根据Bean名称获取实例
	 * @param name  Bean注册名称
	 * @return bean实例
	 * @throws BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		return (T) applicationContext.getBean(name);
	}

	/**
	 * 根据Bean名称获取实例
	 * @param name  Bean注册名称
	 * @return bean实例
	 * @throws BeansException
	 */
	@SuppressWarnings({ "unchecked" })
	public static <T> T getBean(Class<?> clazz) throws BeansException {
		return (T) applicationContext.getBean(clazz);
	}
	
	
	
	/**
	 * 生成指定长度的随机字符串（0--9,A--Z,a--Z）
	 */
	public static String genRandom(int length) {
		StringBuffer buffer = new StringBuffer();
		SecureRandom random = null;
		try {
			random = SecureRandom.getInstance("SHA1PRNG");
		} catch (NoSuchAlgorithmException e) {
			log.error(e.getMessage(), e);
			return null;
		}
		int i = 0;
		int c;
		while (i < length) {
			c = random.nextInt(122);
			if ((48 <= c && c <= 57) || (65 <= c && c <= 90)
					|| (97 <= c && c <= 122)) {
				buffer.append((char) c);
				i++;
			}
		}
		return buffer.toString();
	}
	
}
